package com.itheima.putige.putige.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.putige.putige.common.R;
import com.itheima.putige.putige.entity.Employee;
import com.itheima.putige.putige.service.EmployeeService;
import com.itheima.putige.putige.utils.EmailUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;
import sun.misc.BASE64Decoder;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Base64;

@RestController
@Slf4j
@RequestMapping("/employee")
public class EmployeeController {
    @Autowired
    private EmailUtils emailUtils;
    @Value("${reggie.weburl}")
    private String weburl;
    @Autowired
    private EmployeeService employeeService;

    @PostMapping("/login")
    public R<Employee> login(@RequestBody Employee employee, HttpServletRequest request) {
        String password = employee.getPassword();
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        LambdaQueryWrapper<Employee> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Employee::getUsername, employee.getUsername());
        Employee emp = employeeService.getOne(lambdaQueryWrapper);
        if (emp == null) {
            return R.error("用户不存在");
        }

        if (!password.equals(emp.getPassword())) {
            return R.error("密码不正确");
        }

        if (emp.getStatus() == 0) {
            return R.error("用户被禁用");
        }
        //request.getSession().setAttribute("employee", emp.getId());
        request.getSession().setAttribute("employee", emp);
        return R.success(emp);
    }

    @PostMapping("/logout")
    public R<String> logout(HttpServletRequest request) {
        request.getSession().removeAttribute("employee");
        return R.success("退出成功");
    }

    @PostMapping()
    public R<String> save(@RequestBody Employee employee) {
        employee.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));
        employeeService.save(employee);
        return R.success("添加成功");
    }

    @GetMapping("/page")
    public R<Page> page(int page, int pageSize, String name) {
        Page<Employee> pageinfo = new Page<>(page, pageSize);
        LambdaQueryWrapper<Employee> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.like(StringUtils.isNotEmpty(name), Employee::getName, name);
        lambdaQueryWrapper.orderByDesc(Employee::getCreateTime);
        employeeService.page(pageinfo, lambdaQueryWrapper);
        return R.success(pageinfo);
    }


    @GetMapping("/{id}")
    public R<Employee> getById(@PathVariable Long id) {
        Employee employee = employeeService.getById(id);
        if (employee != null) {
            return R.success(employee);
        }
        return R.error("没查到信息");
    }

    @PutMapping
    public R<String> update(@RequestBody Employee employee) {
        employeeService.updateById(employee);
        return R.success("修改成功");
    }

    @PostMapping("/repwd")
    public R<String> rePwd(@RequestBody Employee employee) throws Exception {
        System.out.println(employee);
        LambdaQueryWrapper<Employee> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Employee::getUsername,employee.getUsername());
        lqw.eq(Employee::getEmail,employee.getEmail());
        Employee emp = employeeService.getOne(lqw);
        if (emp == null){
            return R.error("用户名或邮箱错误");
        }
        long endTimes = System.currentTimeMillis()+1*24*3600*1000;
        String para = employee.getUsername()+";"+employee.getEmail()+";"+endTimes;
        //先加密，再url转码,顺序不能修改
        /*String encode = "http://rg.zcscloud.cn/findPwd/" + UrlUtil.getURLEncoderString(DesUtil.encrypt(para));*/
        String base64encodedString = Base64.getEncoder().encodeToString(para.getBytes("UTF-8"));
        //String base64encodedString = Base64.getUrlEncoder().encodeToString(para.getBytes("utf-8"));
        System.out.println("Base64 编码字符串 (URL) :" + base64encodedString + "<====================================================================================");


        String msg = "您好:\r\n"+employee.getUsername() + ",您在"+"["+ weburl +"]申请找回密码的请求已通过,重设密码地址:\r\n"+"http://"+weburl+"/employee/findpwd/"+base64encodedString+"\r\n" +
                "如果上面的连接无法点击,您也可以复制连接,粘贴到您的浏览器地址栏进行访问.\r\n如果您没有操作该业务,请忽略并删除此邮件\r\n谢谢!";
        emailUtils.sendEmail(employee.getEmail(),msg,"找回密码");
        return R.success("请求发送成功,请前往邮箱查看");
    }


    @GetMapping("/findpwd/{codeString}")
    public void findPwd(@PathVariable String codeString, HttpServletRequest request, HttpServletResponse response) throws Exception {
        System.out.println("==============================================================================================");
        System.out.println(codeString);
        //此处直接des解码
        String decode = new String( new BASE64Decoder().decodeBuffer(codeString), "UTF-8");
        System.out.println(decode+ "<=============================================================================================");
        //获取信息
        String[] split = decode.split(";");
        String username = split[0];
        String email = split[1];
        Long time = Long.valueOf(split[2]);

        LambdaQueryWrapper<Employee> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Employee::getUsername,username);
        lqw.eq(Employee::getEmail,email);
        Employee emp = employeeService.getOne(lqw);
        if (emp != null){
            long endTimes = System.currentTimeMillis();
            if (time > endTimes){
                Cookie cookie = new Cookie("key%",codeString);
                response.addCookie(cookie);
                request.getRequestDispatcher("/backend/page/login/repwd.html").forward(request,response);
            }
        }

    }

    @PostMapping("/findpwd")
    public R<String> resPwd(@RequestBody Employee employee) throws IOException {
        String key = employee.getEmail();
        String decode = new String( new BASE64Decoder().decodeBuffer(key), "UTF-8");
        System.out.println("decode = " + decode);
        //获取信息
        String[] split = decode.split(";");
        String username = null;
        String email = null;
        Long time = null;
        try {
            username = split[0];
            email = split[1];
            time = Long.valueOf(split[2]);
        } catch (NumberFormatException e) {
            return R.error("无效链接");
        }
        //password = DigestUtils.md5DigestAsHex(password.getBytes());
        String pwd = employee.getPassword();
        pwd = DigestUtils.md5DigestAsHex(pwd.getBytes());
        LambdaQueryWrapper<Employee> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Employee::getUsername,username);
        lqw.eq(Employee::getEmail,email);
        Employee emp = employeeService.getOne(lqw);
        if (emp != null){
            long endTimes = System.currentTimeMillis();
            if (time > endTimes){
                emp.setPassword(pwd);
                employeeService.updateById(emp);
                return R.success("密码重置成功");
            }
        }

        return R.error("链接已失效");
    }
}
